package com.lz.seata.controller;

import com.lz.seata.domain.CodeMsg;
import com.lz.seata.domain.Order;
import com.lz.seata.domain.ResultVO;
import com.lz.seata.service.IOrderService;
import com.lz.seata.service.IProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Description: OrderController
 * @Date: 2020/5/4 12:05
 * @Author: LiZhen
 * @Version: 1.0
 */
@RestController
public class OrderController {
    @Resource
    private IProductService productService;
    @Resource
    private IOrderService orderService;
    @PostMapping("/orders/{pid}/{number}")
    public ResultVO create(@PathVariable Integer id, @PathVariable Integer number) {
        try {

            Order order = new Order();
            ResultVO resultVO = productService.findByPid(id);

            Map map = (Map) resultVO.getData();
            Integer stock = (Integer) map.get("stock");
            if(stock > 0) {
                // 下单
                order.setProductId(id);
                order.setProductName((String) map.get("pname"));
                order.setPrice((Double) map.get("price"));
                order.setNumber(number);
                order.setUserId(1);
                order.setUserName("邓紫棋");
                orderService.create(order);
                ResultVO resultVO2 = productService.deductStock(id, number);

                if(resultVO2.getCode() == 200 ) {
                    return ResultVO.success(order);
                } else {
                    return ResultVO.error(CodeMsg.PRODUCT_SERVER_ERROR);
                }
            } else {
                throw new RuntimeException("下单失败，库存不足");
            }
        } catch (Exception e) {
            return ResultVO.error(e.getMessage());
        }

    }

    @GetMapping("/orders/testloadbalance")
    public ResultVO testLoadBalance() {
        ResultVO resultVO = productService.testLoadBalance();
        return resultVO;
    }

}
